<template>
  <el-card class="questions-new">
    <!--    标题(判断是否有路由传递的ID)-->
    <div slot="header" class="header">
      试题{{ queryObj.id ? '编辑' : '录入' }}
    </div>
    <!--    /标题-->

    <el-form
      ref="refForm"
      label-width="100px"
      :model="formData"
      :rules="formRules"
    >
      <!--     学科-->
      <el-form-item label="学科：" prop="subjectID">
        <el-select
          class="w400"
          v-model="formData.subjectID"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="v in subjectList"
            :key="v.id"
            :label="v.subjectName"
            :value="v.id"
          />
        </el-select>
      </el-form-item>
      <!--     /学科-->

      <!--      目录-->
      <el-form-item label="目录：" prop="catalogID">
        <el-select
          class="w400"
          v-model="formData.catalogID"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="v in directoryListing"
            :key="v.value"
            :label="v.label"
            :value="v.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!--      /目录-->

      <!--      企业-->
      <el-form-item label="企业：" prop="enterpriseID">
        <el-select
          class="w400"
          v-model="formData.enterpriseID"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="v in enterpriseList"
            :key="v.id"
            :label="v.company"
            :value="v.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!--      / 企业-->

      <!--      城市-->
      <el-form-item label="城市：" prop="city">
        <el-select
          v-model="formData.province"
          placeholder="请选择"
          clearable
          @change="handleProvince"
          style="width: 195px; margin-right: 10px"
        >
          <el-option
            v-for="item in citySelect.province"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
        <el-select
          v-model="formData.city"
          placeholder="请选择"
          clearable
          style="width: 195px"
        >
          <el-option
            v-for="item in citySelect.cityDate"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <!--      /城市-->

      <!--      方向-->
      <el-form-item label="方向：" prop="direction">
        <el-select
          class="w400"
          v-model="formData.direction"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="(item, index) in direction"
            :key="index"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <!--      /方向-->

      <!--      题型-->
      <el-form-item label="题型：" prop="questionType">
        <el-radio
          style="width: 100px"
          v-model="formData.questionType"
          v-for="v in questionType"
          :key="v.value"
          :label="v.value + ''"
          >{{ v.label }}
        </el-radio>
      </el-form-item>
      <!--      /题型-->

      <!--      难度-->
      <el-form-item label="难度：" prop="difficulty">
        <el-radio
          style="width: 100px"
          v-model="formData.difficulty"
          v-for="v in difficulty"
          :key="v.value"
          :label="v.value+''"
          >{{ v.label }}
        </el-radio>
      </el-form-item>
      <!--      / 难度-->

      <!--      题干-->
      <el-form-item label="题干：" prop="question">
        <quill-editor
          v-model="formData.question"
          ref="myQuillEditor"
          :options="editorOption"
        >
        </quill-editor>
      </el-form-item>
      <!--       /题干-->

      <!-- 选项 单选 多选 简答 切换-->
      <el-form-item
        label="选项："
        v-if="formData.questionType !== '3'"
        label-width="5%"
      >
        <!-- 选项组 -->
        <div
          v-for="item in formData.options"
          :key="item.code"
          style="margin-bottom: 20px"
        >
          <!-- 单选 -->
          <el-radio
            v-model="item.isRight"
            v-if="formData.questionType === '1'"
            :label="true"
            @change="changeRidio(item)"
            >{{ item.code }}</el-radio
          >
          <!-- 多选 -->
          <el-checkbox
            v-model="item.isRight"
            v-if="formData.questionType !== '1'"
            :label="true"
            style="width: 50px"
            >{{ item.code }}
          </el-checkbox>

          <!-- 输入题目 -->
          <el-input style="width: 25%" v-model="item.title"></el-input>
          <!-- 图片上传 -->
          <!-- <el-upload action="#">123</el-upload> -->
        </div>

        <!-- 添加按钮 -->
        <el-button
          type="danger"
          :disabled="formData.questionType === '1'"
          @click="addOption"
          size="small"
        >
          +增加选项与答案
        </el-button>
      </el-form-item>

      <!--      解析视频-->
      <el-form-item label="解析视频：">
        <el-input
          class="w400"
          v-model="formData.videoURL"
          placeholder="请输入内容"
        ></el-input>
      </el-form-item>
      <!--      /解析视频-->

      <!--     答案解析-->
      <el-form-item label="答案解析：" prop="answer">
        <quill-editor
          v-model="formData.answer"
          ref="myQuillEditor2"
          :options="editorOption"
        >
        </quill-editor>
      </el-form-item>
      <!--     /答案解析-->

      <!--     题目备注-->
      <el-form-item label="题目备注：">
        <el-input
          class="w400"
          type="textarea"
          :rows="7"
          col="20"
          v-model="formData.remarks"
          placeholder="请输入内容"
        >
        </el-input>
      </el-form-item>
      <!--     /题目备注-->

      <!--      试题标签-->
      <el-form-item label="试题标签：" prop="tags">
        <el-select
          class="w400"
          v-model="formData.tags"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请选择标签"
        >
          <el-option
            v-for="(v, i) in tagList"
            :key="i"
            :label="v.label"
            :value="v.label"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!--      /试题标签-->

      <!--    提交按钮-->
      <el-form-item>
        <el-button type="primary" @click="onSubmit">
          确认{{ queryObj.id ? '编辑' : '录入' }}
        </el-button>
      </el-form-item>
      <!--    /提交按钮-->
    </el-form>
  </el-card>
</template>

<script>
import { list as getSubjects } from '@/api/hmmm/subjects'
import { simple as getDirectorys } from '@/api/hmmm/directorys'
import { list as getCompanys } from '@/api/hmmm/companys'
import { simple as getTagsList } from '@/api/hmmm/tags'
import { add, update, detail } from '@/api/hmmm/questions'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { questionType, direction, difficulty } from '@/api/hmmm/constants'
export default {
  name: 'newques',
  data () {
    return {
      // 表单数据
      formData: {
        subjectID: '', // 学科 id
        catalogID: '', // 目录 id
        enterpriseID: '', // 企业ID
        province: '', // 企业所在地省份
        city: '', // 企业所在城市
        direction: '', // 方向
        questionType: '1', // 试题类型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        videoURL: '',
        answer: '',
        remarks: '', // 题目备注
        tags: '' // 标签名称
      },
      // 学科列表
      subjectList: [],
      // 目录列表
      directoryListing: [],
      // 企业列表
      enterpriseList: [],
      // 城市
      citySelect: {
        province: [],
        cityDate: []
      },
      // 方向
      direction,
      // 题型
      questionType,
      // 难度
      difficulty,
      // 选项
      optionResults: [],
      // 选项数量
      optionNum: 4,
      // 标签数据
      tagList: [],
      // A的Ascll码
      serialNumber: 65,
      //  富文本配置
      editorOption: {
        modules: {
          toolbar: [
            'bold',
            'italic',
            'underline',
            'strike',
            { list: 'ordered' },
            { list: 'bullet' },
            'blockquote',
            'code-block',
            'image',
            'link'
          ]
        },
        placeholder: '输入内容...'
      },
      // 表单验证
      formRules: {
        subjectID: [this.checkRequired('学科')],
        catalogID: [this.checkRequired('目录')],
        enterpriseID: [this.checkRequired('企业')],
        city: [this.checkRequired('城市')],
        direction: [this.checkRequired('方向')],
        questionType: [this.checkRequired('题型')],
        difficulty: [this.checkRequired('难度')],
        question: [this.checkRequired('题干')],
        answer: [this.checkRequired('答案解析')],
        tags: [this.checkRequired('试题标签', 'blur')]
      },
      // 判断是添加还是修改
      queryObj: this.$route.query
    }
  },
  created () {
    this.getSubjectsList()
    this.getDirectorsList()
    this.getCompanysList()
    this.getCityData()
    this.getTages()
    if (this.queryObj.id) {
      return this.getEditForm()
    }
  },
  methods: {
    // 单选
    changeRidio (item) {
      this.formData.options.forEach((item) => {
        item.isRight = false
      })
      item.isRight = true
    },
    // 添加选项
    addOption () {
      this.formData.options.push({
        isRight: false,
        code: String.fromCharCode(this.formData.options.length + 65),
        title: '',
        img: ''
      })
    },

    // 编辑数据获取
    async getEditForm () {
      const { data } = await detail({ id: this.queryObj.id })
      // 将options中的isRight转换为布尔值
      data.options.forEach((item) => {
        item.isRight = Boolean(item.isRight)
      })
      this.formData = data
      const arr = []
      data.options.forEach((item) => {
        if (item.isRight) {
          arr.push(item.code)
        }
      })
      // 将单选中的数据转换为数组
      this.optionResults = this.formData.questionType === 1 ? arr.join() : arr
      // 将字符串转换为数组，添加新标签的时候是添加数组
      this.formData.tags = this.formData.tags.split(',')
    },

    // 获取学科
    async getSubjectsList () {
      const {
        data: { items }
      } = await getSubjects()
      this.subjectList = items
    },

    // 获取目录
    async getDirectorsList () {
      const { data } = await getDirectorys()
      this.directoryListing = data
    },

    // 获取企业名称
    async getCompanysList () {
      const {
        data: { items }
      } = await getCompanys()
      this.enterpriseList = items
    },

    // 获取省
    getCityData: function () {
      this.citySelect.province = provinces()
    },

    // 选省获取到市
    handleProvince: function (e) {
      this.citySelect.cityDate = citys(e)
      this.formData.city = this.citySelect.cityDate[0]
    },

    // 获取标签
    async getTages () {
      const { data } = await getTagsList()
      this.tagList = data
    },

    // 封装表单验证
    checkRequired (value, trigger = ['blur', 'change']) {
      return { required: true, message: `${value}不能为空`, trigger }
    },
    // 提交
    async onSubmit () {
      // 表单验证
      await this.$refs.refForm.validate()
      this.formData.tags = this.formData.tags.join(',')
      // 如果有 id 就是编辑调用 update() 否则就是新增调用 addItem()
      try {
        const { status } = await (this.queryObj?.id
          ? update(this.formData)
          : add(this.formData))
        this.$message.success(this.queryObj.id ? '编辑成功' : '录入成功')
        status === 200 &&
          this.$router.push(
            this.queryObj.id?.or === 'choice'
              ? '/questions/choice'
              : '/questions/list'
          )
      } catch (e) {
        this.formData.tags = this.formData.tags.split(',')
        this.$message.error(this.queryObj.id ? '编辑失败' : '录入失败')
      }
    }
  },

  // 修改富文本的高度
  mounted () {
    this.editor.container.style.height = '200px'
    this.editor2.container.style.height = '200px'
  },
  // 获取到富文本
  computed: {
    editor () {
      return this.$refs.myQuillEditor.quill
    },
    editor2 () {
      return this.$refs.myQuillEditor2.quill
    }
  },
  watch: {
    // 选项发生改变，添加到formDate中
    optionNum (newValue, oldValue) {
      console.log(newValue)
      for (let i = 0; i < newValue - oldValue; i++) {
        this.formData.options.push({
          isRight: false,
          // 将字符串转化为ascll码
          code: String.fromCharCode(this.serialNumber++),
          title: '',
          img: ''
        })
      }
    }
  }
}
</script>

<style scoped lang="less">
.form_width {
  width: 500px;
}

.quill {
  margin-left: 40px;
  margin-bottom: 50px;
  height: 150px;
}
</style>
